<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Promocion extends CI_Controller {
    
    public $ruta_template;
    public $fields_table;
    public $fields_form;
    public $validate_fields;

    function __construct(){
        parent::__construct();
        $this->lang->load('lang/prm_'.$this->config->item('language'), $this->config->item('language'));
        $this->load->model('promocion_model');
        $this->load->library('form_validation');
        $this->ruta_template = array('ruta' => site_url().'public/'.$this->template->getActiveTemplate());
        $this->template->write_view('footer', 'footer');
        $this->template->write_view('header', 'header');
        $this->template->write_view('_scripts', 'js', $this->ruta_template);
        $this->template->write_view('_styles', 'css', $this->ruta_template);
        $this->fields_table = array('', 'prm_idpromocion', 'prm_titulo', 'prm_imagen', 'prm_descripcion', 'prm_activo');
        $this->fields_form = array('prm_idpromocion', 'prm_titulo', 'prm_imagen', 'prm_descripcion', 'prm_activo');
        $this->validate_fields = array('', 'trim|required|xss_clean', 'trim|required', 'trim|required|xss_clean', '');
    }

    public function getTemplate(){
        $row = '<tr value="%TABLEID%" bgcolor="white">';
        return array ('table_open'  => '<table id="tabla">', 'row_start'  => $row, 'row_alt_start'  => $row);
    }

    public function index(){
        $this->load->library('table');
        $this->table->set_heading(array_slice($this->fields_table, 1));
        $this->table->set_template($this->getTemplate());
        $data['tabla'] = $this->table->generate($this->promocion_model->getPromociones(array_slice($this->fields_table, 1)), strtolower(__CLASS__), true);
        $this->template->write_view('content', 'content/promocion', $data);
        $this->template->render();
    }

    public function borrar($codigo = ''){
        $this->promocion_model->borrar($codigo);
        redirect('promocion');
    }
    
    public function agregar(){
        $this->load->library('table');
        $this->load->library('form_creator');

        $this->form_creator->setTabla(strtolower(__CLASS__));
        $hidden  = $this->form_creator->pintaCampo(array('field' => "p_accion", 'type' => 'HDN', 'value' => 'C'));
        $campos = array();
        for($x = 1; $x < count($this->fields_form); $x++){
            $campos[] = lang($this->fields_form[$x]);
            $campos[] = $this->switch_comun($this->fields_form[$x]);
        }

        $new_list = $this->table->make_columns($campos, 4);
        $data['tabla'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        $this->template->write_view('content', 'content/promocion_ce', $data);
        $this->template->render();
    }

    public function editar($indice = ''){
        $this->load->library('table');
        $this->load->library('form_creator');

        $usuario = $this->promocion_model->getPromociones($this->fields_form, $indice);
        $this->form_creator->setTabla(strtolower(__CLASS__));
        $row = $usuario->row_array();
        $hidden  = $this->form_creator->pintaCampo(array('field' => $this->fields_form[0], 'type' => 'HDN', 'value' => $row[$this->fields_form[0]]));
        $hidden .= $this->form_creator->pintaCampo(array('field' => "p_accion", 'type' => 'HDN', 'value' => 'E'));
        $hidden .= $this->form_creator->pintaCampo(array('field' => "p_campos", 'type' => 'HDN', 'value' => $indice));
        $campos = array();
        for($x = 1; $x < count($this->fields_form); $x++){
            $campos[] = lang($this->fields_form[$x]);
            $campos[] = $this->switch_comun($this->fields_form[$x], $row[$this->fields_form[$x]]);
        }
        $new_list = $this->table->make_columns($campos, 4);
        $data['tabla'] = $hidden.$this->table->generate($new_list, strtolower(__CLASS__));
        $this->template->write_view('content', 'content/promocion_ce', $data);
        $this->template->render();
    }

    public function guardar(){
        $accion = $_POST['p_accion'][0];
        $parametros = array();
        /*for($z = 1; $z < count($this->validate_fields); $z++){
            $this->form_validation->set_rules($this->fields_form[$z].'[]', 'lang:'.$this->fields_form[$z], $this->validate_fields[$z]);
        }
        if($this->form_validation->run() == FALSE){
            if($accion == 'C'){
                redirect('promocion/agregar');
            }else if($accion == 'E'){
                $this->editar($_POST['p_campos'][0]);
                return;
            }
	}*/
        $entro_en_check_activo = false;
        foreach ($this->input->post() as $key => $value) {
            for($i = 0; $i < count($value); $i++){
                if(strpos($key, "prm") !== false){
                    if($value[$i] != ''){
                        if(strpos($key, "prm_activo") !== false){
                            $parametros[$i][$key] = ($value[$i] == 'on' ? 'S' : 'N');
                            $entro_en_check_activo = true;
                        }else{
                            $parametros[$i][$key] = $value[$i];
                        }
                    }
                }
            }
        }
        if(!$entro_en_check_activo){
            $parametros[count($parametros)-1]['prm_activo'] = 'N';
        }
        try{
            $resultado = $this->subir_imagen_promocion();
            if($resultado != null){
                $parametros[count($parametros)-1]['prm_imagen'] = $resultado;
            }

            if($accion == 'C'){
                $this->promocion_model->guardar($parametros[0]);
                $this->session->set_flashdata('message', lang('successfully_created'));
                redirect('promocion', 'refresh');
            }else if($accion == 'E'){
                $this->promocion_model->actualizar($parametros[0]);
                redirect('promocion', 'refresh');
            }
        }catch (Exception $e){
            $this->session->set_flashdata('message', 'Se ha producido un error');
            redirect('promocion', 'refresh');
        }
    }
    
    function subir_imagen_promocion(){
        if($_FILES['prm_imagen']['name'] != ''){
            $fecha = new DateTime();
            $filename = $fecha->getTimestamp();
            $extension = substr(strrchr($_FILES['prm_imagen']['name'], '.'), 1);
            $config['upload_path'] = $this->config->item('ruta_uploads')."promociones/";
            $config['allowed_types'] = 'gif|jpg|jpeg|png';
            $config['max_size'] = '2000';
            $config['max_width'] = '2048';
            $config['max_height'] = '1058';
            $config['file_name'] = $filename;

            $this->load->library('upload', $config);

            if(!is_dir($config['upload_path'])){
                mkdir($config['upload_path'], 0777, true);
            }
            
            if($this->upload->do_upload('prm_imagen')){
                $this->load->library('image_lib');
                $conf['source_image'] = $config['upload_path'].$filename.".".$extension;
                $conf['source_folder'] = $config['upload_path'];
                $conf['width'] = '630';
                $conf['height'] = '330';
                $conf['maintain_ratio'] = false;
                $conf['dynamic_output'] = false;
                $conf['quality'] = '75%';    // calidad de la imagen
                $conf['create_thumb'] = false;
                $this->image_lib->initialize($conf);
                $this->image_lib->resize();            
                return $filename.".".$extension;
            }
            return null;
        }else{
            return null;
        }
    }
    
    function switch_comun($field = '', $value = ''){
        $this->load->helper('directory');
        $this->load->helper('settings');
        switch ($field) {
            case 'prm_idpromocion':
                return $this->form_creator->pintaCampo(array('field' => $field, 'type' => 'HDN', 'value' => $value));
                break;
            case 'prm_imagen':
                return $this->form_creator->pintaCampo(array('field' => $field, 'type' => 'FIL', 'style' => 'size="50"'));
                break;
            default:
                return $this->form_creator->pintaCampo(array('field' => $field, 'value' => $value));
        }
    }
}

?>
